//
//  SearchController.m
//  TrainTree
//
//  Created by wanghui on 2017/9/20.
//  Copyright © 2017年 YouYeShu. All rights reserved.
//

#import "SearchController.h"
#import "CategorySearchCell.h"
#import "RecordsSearchCell.h"
#import "SearchCourseCell.h"
#import "SearchTool.h"
#import "SearchPoint.h"
#import "ResultSectionHeader.h"
#import "SearchRequestManager.h"
#import "SearchMainModel.h"
#import "QuickLookFileController.h"
#import "CourseDetailController.h"
#import "CourseAudioVideoController.h"
static NSInteger   const SearchRecordNum = 10;

@interface SearchController ()<UITableViewDelegate, UITableViewDataSource,RecordClickDelegate,UITextFieldDelegate,CategorySearchDelegate,QuickLookDelegate>
{
    SearchMainModel *_mainModel;// 总Model
}
@property (weak, nonatomic) IBOutlet UIView *searchView;
@property (weak, nonatomic) IBOutlet UITextField *searchTextField;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
// 历史记录
@property (nonatomic,strong)NSMutableArray *recordMutableArray;
/**搜索的类型*/
@property (nonatomic, assign) SearchType searchType;

@end

@implementation SearchController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setSearchUI];
    self.searchTextField.delegate = self;

    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"RecordsSearchCell" bundle:nil] forCellReuseIdentifier:@"RecordsSearchCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"CategorySearchCell" bundle:nil] forCellReuseIdentifier:@"CategorySearchCell"];

    [self.tableView registerNib:[UINib nibWithNibName:@"SearchTool" bundle:nil] forCellReuseIdentifier:@"SearchTool"];
    [self.tableView registerNib:[UINib nibWithNibName:@"SearchPoint" bundle:nil] forCellReuseIdentifier:@"SearchPoint"];
    [self.tableView registerNib:[UINib nibWithNibName:@"SearchCourseCell" bundle:nil] forCellReuseIdentifier:@"SearchCourseCell"];

    self.searchType = SearchTypeSearch;
    [SearchRecord createSearchRecord];
    [self getRecord];
}

#pragma mark - 点击清空搜索框
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    self.searchType = SearchTypeSearch;
    [self getRecord];

    [self.tableView reloadData];
    return YES;
}

#pragma  mark - 点击搜索
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self  saveRecord:textField.text];
    self.searchType = SearchTypeResult;
    [self.view endEditing:YES];
    [self requestSearchData:textField.text];

    return YES;
}

#pragma mark - 请求数据
- (void)requestSearchData:(NSString *)str
{
    WeakSelf(ws);
    [SearchRequestManager requestSearchDataWithKeyWord:str responseBlock:^(id JSONData, NSError *error, NSURLSessionDataTask *dataTask) {
        if (JSONData) {
            _mainModel = [SearchMainModel mj_objectWithKeyValues:JSONData[@"d"]];
            if (_mainModel.contentPoint.count == 0 && _mainModel.tools.count == 0 && _mainModel.lesson.count == 0) {
                [SVProgressHUD showWithStatus:@"搜索无结果"];
            }
            [ws.tableView reloadData];
        }
    }];
}

#pragma  mark - 创建搜索框部分UI
- (void)setSearchUI
{
    self.searchView.layer.cornerRadius = 14.0f;
    self.searchView.layer.masksToBounds = YES;
    self.searchView.layer.borderColor = rgb(216.0f, 216.0f, 216.0f).CGColor;
    self.searchView.layer.borderWidth = 1.0f;

    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 24)];
    leftBtn.imageEdgeInsets = UIEdgeInsetsMake(0,8,0,2);
    [leftBtn setImage:ImageNamed(@"search") forState:UIControlStateNormal];
    self.searchTextField.leftView = leftBtn;
    self.searchTextField.leftViewMode = UITextFieldViewModeAlways;
}
#pragma mark - 返回上个页面
- (IBAction)dismissCurrentPage:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 拿到本地存储的搜索记录
- (void)getRecord
{
    self.recordMutableArray = [NSMutableArray arrayWithArray:[[SearchRecord shareSearchRecord]getSearchRecord]];
}

#pragma mark - 存储搜索记录
- (void)saveRecord:(NSString *)text
{
    if ([_recordMutableArray containsObject:text]) {

        [_recordMutableArray removeObject:text];
//        [_recordMutableArray addObject:text];
        [_recordMutableArray insertObject:text atIndex:0];
    }else{// 不包含的
        // 小于10个
        if (_recordMutableArray.count < SearchRecordNum) {
//            [_recordMutableArray addObject:text];
            [_recordMutableArray insertObject:text atIndex:0];

        }else{
            [_recordMutableArray removeLastObject];
            [_recordMutableArray insertObject:text atIndex:0];
//            [_recordMutableArray removeObjectAtIndex:0];
//            [_recordMutableArray addObject:text];

        }
    }
    [[SearchRecord shareSearchRecord] saveSearchRecord:_recordMutableArray];

}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(self.searchType == SearchTypeResult) {
        int count = 0;
        if (_mainModel.contentPoint.count > 0) {
            count += 1;
        }
        if (_mainModel.lesson.count > 0) {
            count += 1;
        }

        if (_mainModel.contentPoint.count > 0) {
            count += 1;
        }

        return count;
    } else {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
        // 搜索结果页
    if(self.searchType == SearchTypeResult) {
        if (section == 0) {
            return _mainModel.lesson.count;
        } else if (section == 1) {
            return _mainModel.contentPoint.count;
        } else {
            return _mainModel.tools.count;
        }
      // 搜索页面
    } else {
        return 2;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.searchType == SearchTypeResult) {
        if(indexPath.section == 1) {// 知识点视频的高度是72;
            return  72.0f;
        } else {// 课程工具的高度都是56；
            return 56.0f;
        }

    } else {
        if (indexPath.row == 0) {
            return 134.0f;
        } else {
            return 116.0f;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(self.searchType == SearchTypeResult) {
        return 25.0f;
    } else {
        return 0.0f;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if(self.searchType == SearchTypeResult) {
        if(section != 2) {
            return 8.0f;
        } else {
            return 0;
        }
    } else {
        return 0.0f;
    }
}

 - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if(self.searchType == SearchTypeResult) {
        if (section == 0 || section == 1) {
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 8)];
            view.backgroundColor = rgb(249.0f, 249.0f, 249.0f);
            return view;
        } else {
            return nil;
        }
    } else{
        return nil;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.searchType == SearchTypeResult) {
        ResultSectionHeader *header = [[ResultSectionHeader alloc] initWithReuseIdentifier:@"ResultSectionHeader"];
        if(section == 0) {
            header.label.text = @"课程";
        } else if (section == 1) {
            header.label.text = @"知识点";
        } else{
            header.label.text = @"工具";
        }
        return header;
    } else {
        return nil;
    }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.searchType == SearchTypeResult) {
        if(indexPath.section == 0) {
            SearchCourseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchCourseCell"];
            if (_mainModel.lesson.count > 0) {
                [cell configWithModel:_mainModel.lesson[indexPath.row]];
            }
            return cell;
        } else if(indexPath.section == 1) {
            SearchPoint *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchPoint"];
            if (_mainModel.contentPoint.count > 0) {
                [cell configWithModel:_mainModel.contentPoint[indexPath.row]];
            }

            return cell;
        } else {
            SearchTool *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchTool"];
            if (_mainModel.tools.count > 0) {
                [cell configWithModel:_mainModel.tools[indexPath.row]];
                cell.delegate = self;
            }
            return cell;
        }
    } else {

        if (indexPath.row == 0) {
            CategorySearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CategorySearchCell"];
            cell.delegate = self;
            return cell;
        } else {
            RecordsSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RecordsSearchCell"];
            cell.delegate = self;
            cell.array = self.recordMutableArray;
            [cell.collectionView reloadData];
            return cell;
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.searchType == SearchTypeResult) {
        if(indexPath.section == 0) {
            CourseDetailController *courseVc = [[CourseDetailController alloc]init];
            if (_mainModel.lesson.count > 0) {
                SearchLessonModel *model = _mainModel.lesson[indexPath.row];
                courseVc.lessonId = model.lessonId ;
            }
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:courseVc animated:YES];

        } else if(indexPath.section == 1) {
            CourseAudioVideoController *audioVc = [[CourseAudioVideoController alloc]init];
            if (_mainModel.contentPoint.count > 0) {
                SearchPointModel *model = _mainModel.contentPoint[indexPath.row];
                audioVc.pointId = model.contentPointId;
            }
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:audioVc animated:YES];

        } else {

        }
    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}
#pragma mark - 点击搜索记录
- (void)recordClick:(NSString *)record
{
    // 拿到搜索文字，触发搜索，刷新列表
    [self  saveRecord:record];

    self.searchType = SearchTypeResult;
    self.searchTextField.text = record;
    [self requestSearchData:record];

}
#pragma mark - 点击分类按钮
- (void)categoryBtnClick:(NSString *)category
{
    [self  saveRecord:category];
    self.searchTextField.text = category;
    self.searchType = SearchTypeResult;

    [self requestSearchData:category];
}

- (void)quickLookFile:(NSString *)filePath
{
    QuickLookFileController *quickLookVc = [[QuickLookFileController alloc]init];
    quickLookVc.filePath = filePath;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:quickLookVc animated:YES];
     
}
- (NSMutableArray *)recordMutableArray
{
    return _recordMutableArray ?: (_recordMutableArray = [[NSMutableArray alloc]initWithCapacity:0]);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
